#!/bin/sh -eu
# checkconfig: 2345 30 70
# description: set up a WireGuard interface simply
### BEGIN INIT INFO
# Provides: wg-quick
# Required-Start: $local-fs $network
# Required-Stop: $local-fs $network
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: set up a WireGuard interface simply
### END INIT INFO

command=/usr/bin/wg-quick

check_interfaces() {
    interfaces=
    shopt -s nullglob
    for f in /etc/wireguard/wg*.conf; do
        f="${f##*/}"
        interfaces="${interfaces} ${f%.*}"
    done
    shopt -u nullglob
    if [ "$interfaces" == "" ]; then
        echo No wireguard configuration files found in /etc/wireguard !
        exit 1
    fi
}

status() {
    check_interfaces
    for interface in $interfaces; do
        /usr/bin/wg show $interface
    done
}

start() {
    check_interfaces
    for interface in $interfaces; do
        description="wg-quick on $interface"
        logfile=/var/log/$interface
        touch $logfile && date >>$logfile
        echo "starting $description ..." | tee -a $logfile
        $command up $interface >>$logfile 2>&1
        echo "... started $description" | tee -a $logfile
    done
}

stop() {
    check_interfaces
    for interface in $interfaces; do
        description="wg-quick on $interface"
        logfile=/var/log/$interface
        touch $logfile && date >>$logfile
        echo "stopping $description ..." | tee -a $logfile
        $command down $interface >>$logfile 2>&1
        echo "... stopped $description" | tee -a $logfile
    done
}

case "${1-}" in
    status) status ;;
    start) start ;;
    restart) stop || true; start ;;
    stop) stop ;;
    *) echo "usage: $0 {status|start|restart|stop}" ;;
esac
